<template>
  <view class="container">
    <!-- 微信小程序开发 -->
    <web-view v-if="openwebview" @message="handleMessage"   id="webviewShop" :src="src" type="top:30px;"></web-view>
	
  </view>
</template>

<script>
import { getUserInfo,openShop,linkShop,closeShop } from '@/api/api';
import { SHOP_H5_PAGE } from '@/config/app.js';
export default {
  data() {
    return {
	  ks:'',
	  isopen_i:0,
	  openwebview:false,
	  intervalItem:null,
      wv: null,
      src: ''
    }
  },
  onLoad(opition) {
    let _this = this
  },
  onReady() {
    const self = this;
    // #ifdef APP-PLUS  
    // #endif  
	
  },
  onShow() {
	  // globalData: {     userInfo: null,     token: '',     // 其他全局数据   },
	  getApp().globalData.webinfo={toWebPage: 'TEST',     toAppPage: '/',};
	  this.toOpenShop();
  },

  methods: {
    setSrcUrl() {
      let _this = this
      let token = uni.getStorageSync('token')
      console.log(token, '[token]');
	  
	  // _this.src = `https://shop.jichacha.vip/h5/pages/index/loading/loading?token=${token}`
	  // _this.src = `https://shop.jichacha.vip/h5/pages/index/loading/loading?token=${token}`
	  // _this.src = 'http://localhost:8080/h5/pages/index/loading?token='+token+'&ks='+this.ks;
	  _this.src = SHOP_H5_PAGE+'/pages/index/loading?token='+token+'&ks='+this.ks;
	  console.log(_this.src, '[src]');
      getUserInfo().then((res) => {
        // _this.src = `https://shop.jichacha.vip/h5/pages/index/loading?token=${token}&id=${res.data.id}`
        console.log('getUserInfo', res);
      }).catch(err => {
        console.log(err, '[]');
        uni.$u.toast('网络超时，请稍后再试');
      })
	  
	  
    },
	toOpenShop(){
		console.log('toOpenShop');
		openShop().then((res) => {
			console.log('openShop',res);
			this.ks = res.data.ks;
			this.openwebview = true;
			this.setSrcUrl();
			this.startLink();
		}).catch(err => {
			console.log(err, '[openShop]');
			uni.$u.toast('异常错误');
			this.openwebview = false;
			this.stopLink();
			uni.reLaunch({
				url:'/pages/tabbar/cameraView'
			})
		  });
	},
	startLink(){
		let i = 0;
		this.intervalItem = setInterval(() => {
					i++;
					console.log('setInterval');
					wx.setStorageSync('webviewInfo', {toAppPage:'-',toWebPage:i});
					let webviewInfo = wx.getStorageSync('webviewInfo');
					console.log('webviewInfo',webviewInfo);
				    //this.sendDataToWebView({ type: 'response', data: 'Hello from Mini Program' });
					this.toLinkShop();
				}, 1000); // 每5秒查询一次
	},
	stopLink(){
		if(!this.openwebview){
			clearInterval(this.intervalItem );
			this.intervalItem  = null; // 重置以便重新启动
		}else{
			setTimeout(this.stopLink() , 1000);
		}
	},
	
	toLinkShop(){
		console.log('toLinkShop');
		
		linkShop({ks:this.ks}).then((res) => {
			console.log('linkShop',res);
			if(res.code){
				if(!res.data.is_open){
					console.log('isopen_i',this.isopen_i);
					if(this.isopen_i<15){
						this.isopen_i++;
					}else{
						uni.$u.toast('网络超时，请稍后再试');
						this.openwebview = false;
						this.stopLink();
						uni.reLaunch({
							url:'/pages/tabbar/cameraView'
						})
					}
				}else{
					this.isopen_i = 0;
					if(res.data.out_time == 0){//关闭商城跳转走
					console.log('关闭商城跳转走');
						this.openwebview = false;
						this.stopLink();
						if(res.data.close_url != ''){
							uni.reLaunch({
								url:res.data.close_url
							})
						}else{
							uni.reLaunch({
								url:'/pages/tabbar/cameraView'
							})
						}
					}
				}
			}else{
				uni.$u.toast('数据异常，请稍后再试!');
				this.openwebview = false;
				this.stopLink();
				uni.reLaunch({
					url:'/pages/tabbar/cameraView'
				})
			}
		}).catch(err => {
			this.openwebview = false;
			this.stopLink();
			console.log(err, '[linkShop]');
			uni.$u.toast('网络超时，请稍后再试');
		  });
	},
    // 接收消息  
    handleMessage(e) {
      const self = this;
      console.log('我收到了网页发来的消息', e.detail.data);
      let data = e.detail.data;
	   console.log('我收到了网页发来的消息,最后的是', data[data.length-1]);
	   if(data.length>3){
		   uni.redirectTo({
				url:'/pages/login/login'
		   })
	   }
	  this.sendDataToWebView({ type: 'response', data: '123123Hello from Mini Program' });
	  if (e.detail.data.type === 'requestData') {
	        this.sendDataToWebView({ type: 'response', data: 'Hello from Mini Program' });
	    }
    },
	sendDataToWebView() {
	      const webViewContext = uni.createWebViewContext('web-view');
	      webViewContext.evaluateJavaScript(
	        `window.receiveData(${JSON.stringify({ type: 'fromUniApp', data: 'Hello' })})`
	      );
	}
  }
}
</script>

<style lang="scss" scoped>
	.container {
	  position: relative; /* 设置相对定位 */
	  width: 100%;
	  height: 100%;
	}
	
	.floating-navigator {
	  position: absolute; /* 设置绝对定位 */
	  top: 10px; /* 距离顶部10px */
	  right: 10px; /* 距离右侧10px */
	  z-index: 1000; /* 设置较高的z-index，确保浮在web-view上面 */
	  /* 其他样式如背景色、字体大小等 */
	}

</style>
